package com.am.server.api.system.dictionary.dao.rdb.impl;

import com.am.server.api.system.dictionary.dao.rdb.DictionaryDao;
import com.am.server.api.system.dictionary.model.dto.DictionaryListQueryDto;
import com.am.server.api.system.dictionary.model.entity.DictionaryEntity;
import com.am.server.api.system.dictionary.model.entity.QDictionaryEntity;
import com.am.server.api.system.dictionary.repository.DictionaryRepository;
import com.querydsl.core.BooleanBuilder;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Repository;

import java.util.Objects;
import java.util.Optional;

/**
 * @author 阮雪峰
 */
@Repository
public class DictionaryDaoImpl implements DictionaryDao {
    private final DictionaryRepository dictionaryRepository;

    public DictionaryDaoImpl(DictionaryRepository dictionaryRepository) {
        this.dictionaryRepository = dictionaryRepository;
    }

    @Override
    public Page<DictionaryEntity> findAll(DictionaryListQueryDto dto) {
        QDictionaryEntity entity = QDictionaryEntity.dictionaryEntity;
        Optional<DictionaryListQueryDto> optional = Optional.of(dto);

        BooleanBuilder booleanBuilder = new BooleanBuilder(entity.id.isNotNull());
        optional.map(DictionaryListQueryDto::getName).ifPresent(name -> booleanBuilder.and(entity.name.contains(name)));

        return dictionaryRepository.findAll(Objects.requireNonNull(booleanBuilder.getValue()), PageRequest.of(dto.getPage() - 1, dto.getPageSize(), Sort.by(Sort.Direction.DESC, entity.id.getMetadata().getName())));
    }

    @Override
    public void save(DictionaryEntity entity) {
        dictionaryRepository.save(entity);
    }

    @Override
    public void deleteById(Long id) {
        dictionaryRepository.deleteById(id);
    }

    @Override
    public Optional<DictionaryEntity> findByCode(String code) {
        return dictionaryRepository.findFirstByCode(code);
    }

    @Override
    public Optional<DictionaryEntity> findByCodeWithId(String code, Long id) {
        return dictionaryRepository.findFirstByCodeAndIdNot(code, id);
    }

    @Override
    public Optional<DictionaryEntity> findById(Long id) {
        return dictionaryRepository.findById(id);
    }
}
